#include "SceneManager.h"
#include "../Renderer/opengl.h"
#include "QuadNode.h"
#include "ResourceManagement/GLtexture.h"

#include "../Renderer/GLShader.h"
#include "../Renderer/GLcamera.h"

CSceneManager::CSceneManager(void)
{
	m_root = NULL;m_font = NULL;
	m_shader = new ShaderPack();
	m_heightmap = NULL;
}

CSceneManager::~CSceneManager(void)
{
	delete m_shader;
	delete m_root;
}


void CSceneManager::Draw()
{
	glDepthFunc(GL_LESS);
	glEnable(GL_DEPTH_TEST);
	int width = 0;int height = 0;

	static GLtexture texGround;
	static GLtexture texRock;

	if(!texGround.m_id)
		texGround.LoadFile("grass.jpg");

	if(!texRock.m_id)
		texRock.LoadFile("rock.jpg");

	if( !m_shader ->GetShader())
		m_shader->CreateAndCompileShaders("GLSL/ground_shading.vs","GLSL/ground_shading.ps");

	m_shader->UseProgram();
	glActiveTextureARB(GL_TEXTURE0);
	glBindTexture( GL_TEXTURE_2D,texGround.m_id );
	m_shader->UniformTexture("texGround",0);
	glActiveTextureARB(GL_TEXTURE1);
	glBindTexture( GL_TEXTURE_2D,texRock.m_id );
	m_shader->UniformTexture("texRock",1);

	this->Render();

	glActiveTextureARB(GL_TEXTURE1);
	glBindTexture(0,1);
	glActiveTextureARB(GL_TEXTURE0);
	glBindTexture(0,0);
	m_shader->UnUseProgram();

	glFlush();
}

void CSceneManager::BuildQuadTree(const char * pFilename)
{
	m_heightmap = new ILimage();
	RECT rc;
	QuadNode *pNode = NULL;

	if( !m_heightmap->GetData())
	{
		m_heightmap->LoadFile(_T("heightmap.bmp"));
	}

	rc.bottom	= -m_heightmap->GetHeight() / 2;
	rc.left		= -m_heightmap->GetWidth() / 2;
	rc.right	= m_heightmap->GetWidth() / 2 - 1;
	rc.top		= m_heightmap->GetHeight() / 2;

	m_root = new ::QuadNode();
	pNode = static_cast<QuadNode*>(m_root);
	
	pNode->BuildSubTree(m_heightmap,rc);
}

void CSceneManager::ExtractRenderables(GLfrustum& fru)
{
	m_root->ExtractRenderables(m_renderables,fru);

	size_t size = m_renderables.m_renderables.Size();

	/*static int nFrameCount = 0;

	m_font->BeginFrame(nFrameCount);
		m_font->PrintTextV(100,100,L"QUAD COUNT:%d",size );
	m_font->EndFrame();*/
}

void CSceneManager::Render()
{
	//ExtractRenderables(m_cam);
	m_renderables.Draw();
}

void CSceneManager::Clear()
{
	m_renderables.Clear();
}

void CSceneManager::AttachFont(GLfont* pFont)
{
	this->m_font = pFont;
}